package com.stylefeng.guns.rest.modular.applications.service;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.rest.common.persistence.dao.LiveAccountMapper;
import com.stylefeng.guns.rest.common.persistence.dao.SendPhoneCodeMapper;
import com.stylefeng.guns.rest.common.persistence.dao.YuoyuenumsMapper;
import com.stylefeng.guns.rest.common.persistence.model.LiveAccount;
import com.stylefeng.guns.rest.common.persistence.model.LiveAccountBO;
import com.stylefeng.guns.rest.common.persistence.model.SendPhoneCode;
import com.stylefeng.guns.rest.common.persistence.model.Yuoyuenums;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.auth.util.MD5Utils;
import com.stylefeng.guns.rest.modular.auth.util.ReaderRelatedUtil;
import com.stylefeng.guns.rest.modular.auth.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import sun.security.mscapi.RSASignature;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

@Service
public class UsersServiceImp implements IUsersService {

    @Autowired
    private LiveAccountMapper liveAccountMapper;
    @Autowired
    private SendPhoneCodeMapper sendPhoneCodeMapper;

    @Autowired
    private YuoyuenumsMapper yuoyuenumsMapper;


    @Override
    public Object login(String account, String password, String device) {
        account = account.trim();
        password = password.trim();
        password = ResultUtil.getSha1(password);
        LiveAccountBO temp = liveAccountMapper.login(account, password);
        if (temp == null) {
            return ResultUtil.error("登录失败,账号或是密码错误");
        } else {
            temp.setToken(ResultUtil.getSha1(account + password + System.currentTimeMillis()));
            LiveAccount liveAccount = new LiveAccount();
            liveAccount.setId(temp.getId());
            liveAccount.setToken(temp.getToken());
            liveAccount.setLoginTime(new Date());
            liveAccount.setDevice(device);
            liveAccountMapper.updateByPrimaryKeySelective(liveAccount);
            //登录时添加数据
            Yuoyuenums yuoyuenums=new Yuoyuenums();
            Yuoyuenums yuoyuenums1 = yuoyuenumsMapper.selectYuoyuenumsByAccount(account);
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(currentTime);
            yuoyuenums.setAccount(account);
            yuoyuenums.setLoginTime(dateString);
            if (yuoyuenums1 == null) {
                yuoyuenumsMapper.insertYuoyuenums(yuoyuenums);
            } else {
                if (!yuoyuenums1.getLoginTime().equals(dateString)) {
                    yuoyuenumsMapper.insertYuoyuenums(yuoyuenums);
                }
            }
            return ResultUtil.success(temp);
        }
    }


    @Override
    public Object register(LiveAccount liveAccount) {
        //只需校验手机是否已经注册过
        String tempAccount = liveAccount.getAccount();
       //JSONObject jsonObject = new JSONObject();
        // 验证账号是否是手机号
       /* if (!ReaderRelatedUtil.isPhone(tempAccount)) {
            return ResultUtil.error("手机号格式不正确");
        }*/
        //检验手机号是否已经注册
        LiveAccount temp = liveAccountMapper.selectByAccount(tempAccount);
        if (temp != null) {
            return ResultUtil.error("该账号已经注册");
        }
        liveAccount.setCreateTime(new Date());
        liveAccount.setPassword(ResultUtil.getSha1(liveAccount.getPassword()));
        liveAccountMapper.insertSelective(liveAccount);
        return ResultUtil.success("注册成功");
        // 验证码输入值的校验
        //SendPhoneCode codeAndTime = sendPhoneCodeMapper.selectCodeAndTime(tempAccount);
        /*if (codeAndTime != null) {
            //Long lastSendTime = codeAndTime.getLastSendTime().getTime();
            //Integer code = codeAndTime.getPhoneCode();
            //Integer usercode = liveAccount.getCode();
            boolean b = ReaderRelatedUtil.codeIsEffective(usercode, code, lastSendTime);
            if (b) {
                liveAccount.setCreateTime(new Date());
                liveAccount.setPassword(ResultUtil.getSha1(liveAccount.getPassword()));
                int a = liveAccountMapper.insertSelective(liveAccount);
                if (a > 0) {

                } else {
                    return ResultUtil.error("注册失败");
                }
            } else {
                return ResultUtil.error("验证码输入有误");
            }
        } else {
            return ResultUtil.error("手机号输入有误");
        }*/
    }

    @Override
    public Object changePassword(String oldPassword, String newPassword, String token) {
        token = token.trim();
        oldPassword = oldPassword.trim();
        newPassword = newPassword.trim();
        if (oldPassword.equals(newPassword)) {
            return ResultUtil.error("新密码和旧密码不能一样");
        }

        LiveAccount temp = liveAccountMapper.selectByToken(token);

        if (null != temp) {
            if (ResultUtil.getSha1(oldPassword).equals(temp.getPassword())) {
                temp.setPassword(ResultUtil.getSha1(newPassword));
                int i = liveAccountMapper.updateByPrimaryKeySelective(temp);
                if (i > 0) {
                    return ResultUtil.success("修改成功");
                } else {
                    return ResultUtil.error("修改失败");
                }
            } else {
                return ResultUtil.error("原密码错误");
            }

        } else {
            return ResultUtil.info("登录信息过期", 104);
        }
    }


    @Override
    public Object sendVerificationCode(String account, String type) {
        JSONObject jsonObject = new JSONObject();
        // 验证账号是否是手机号
        if (!ReaderRelatedUtil.isPhone(account)) {
            return ResultUtil.error("手机号格式不正确");
        }
        //检验手机号是否已经注册
        LiveAccount temp1 = liveAccountMapper.selectByAccount(account);
        if ("1".equals(type) && temp1 != null) {
            return ResultUtil.error("手机号已经注册");
        }
        // 时间限制处理，验证码10分钟内只发一次
        Long lastSendTime = sendPhoneCodeMapper.selectLastSendTime(account);
        int code = 0;
        if (lastSendTime == null) {
            code = ReaderRelatedUtil.sendPhoneCode(account);
        } else {
            boolean b = ReaderRelatedUtil.verificationCodeLimitation(lastSendTime);
            if (b) {
                code = ReaderRelatedUtil.sendPhoneCode(account);
            } else {
                // 不发
                return ResultUtil.success("验证码已发送");
            }
        }
        SendPhoneCode temp = new SendPhoneCode();
        temp.setAccount(account);
        temp.setPhoneCode(code);
        temp.setLastSendTime(new Date());
        int i = sendPhoneCodeMapper.addOrUpdate(temp);
        if (i > 0) {
            return ResultUtil.success("验证码发送成功");
        } else {
            return ResultUtil.error("验证码发送失败");
        }
    }

    @Override
    public Object resetPassword(String code, String account, String newPassword) {
        JSONObject jsonObject = new JSONObject();
        String tempAccount = account.trim();
        Long lastSendTime = sendPhoneCodeMapper.selectLastSendTime(tempAccount);
        SendPhoneCode sendPhoneCode = sendPhoneCodeMapper.selectCodeAndTime(account);
        LiveAccount temp = liveAccountMapper.selectByAccount(tempAccount);
        if (sendPhoneCode == null) {
            return ResultUtil.error("该账号不存在");
        }
        //根据账号去查询code是否等于发送的code
        String phoneCode = sendPhoneCode.getPhoneCode().toString();
        if (!phoneCode.equals(code)) {
            return ResultUtil.error("验证码错误");
        }
        // 验证重置操作是否在10分钟内完成
        if (lastSendTime == null) {
            return ResultUtil.error("该账号不存在");
        } else {
            boolean b = ReaderRelatedUtil.verificationCodeLimitation(lastSendTime);
            if (!b) {
                // 执行重置
                temp.setPassword(ResultUtil.getSha1(newPassword));
                int i = liveAccountMapper.updateByPrimaryKeySelective(temp);
                if (i > 0) {
                    return ResultUtil.success("重置成功");
                } else {
                    return ResultUtil.error("重置失败");
                }
            } else {
                return ResultUtil.error("验证失效，请重新验证");
            }
        }
    }

    @Override
    public Object tokenLogin(String token, String device) {

        LiveAccountBO temp = liveAccountMapper.tokenLogin(token);

        if (null == temp) {
            return ResultUtil.info("登录信息已过期", 104);
        } else {
            LiveAccount liveAccount = new LiveAccount();
            liveAccount.setId(temp.getId());
            liveAccount.setLoginTime(new Date());
            liveAccount.setDevice(device);
            liveAccountMapper.updateByPrimaryKeySelective(liveAccount);
            //登录时添加数据
            Yuoyuenums yuoyuenums=new Yuoyuenums();
            Yuoyuenums yuoyuenums1 = yuoyuenumsMapper.selectYuoyuenumsByAccount(temp.getAccount());
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(currentTime);
            yuoyuenums.setAccount(temp.getAccount());
            yuoyuenums.setLoginTime(dateString);
            if (yuoyuenums1 == null) {
                yuoyuenumsMapper.insertYuoyuenums(yuoyuenums);
            } else {
                if (!yuoyuenums1.getLoginTime().equals(dateString)) {
                    yuoyuenumsMapper.insertYuoyuenums(yuoyuenums);
                }
            }
            return ResultUtil.success(temp);
        }
    }

    @Override
    public Object isVip(String token) {
        LiveAccount temp = liveAccountMapper.selectByToken(token);

        if (null == temp) {
            return ResultUtil.info("登录信息已过期", 104);
        } else {
            long date = System.currentTimeMillis();

            if (null == temp.getVipTime()) {
                return ResultUtil.success(false);
            }

            long vipTime = temp.getVipTime().getTime();

            if (date > vipTime) {
                return ResultUtil.success(false);
            } else {
                return ResultUtil.success(true);
            }
        }
    }
}
